package handlers.echo;

import handlers.BidirectionalConnectionHandler;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

public class ProxyHandler implements BidirectionalConnectionHandler{
    
	private final int BUFSIZE = 100;
	
    @Override
    public void handle(final Socket client, final Socket server) throws IOException {
    	Thread send=new Thread(){
    		@Override
    		public void run() {
    			System.out.println( "se crea el THREAD que envia desde el cliente al server destino");
    			try {
					processData(client,server);
					System.out.println("el cliente cerro la conexion");
				} catch (IOException e) {
				} finally{
					if(!server.isClosed()){
						try {
							server.close();
						} catch (IOException e1) {
							e1.printStackTrace();
						}
					}
					finish();
				}
    		}
    		
    		private void finish() {
    			this.interrupt();
    			System.out.println("se cierra el thread");
			}
    	};
    	
    	send.start();
    	
    	try {
    		processData(server,client);
    	} catch (Exception e) {
    	} finally{
    		send.interrupt();
    		if(!client.isClosed()){
    			client.close();
    		}
    	}

    	
    }
    
    public void processData(Socket from, Socket to) throws IOException{
    	InputStream in = from.getInputStream();
    	OutputStream out = to.getOutputStream();

    	int recvMsgSize;   // Size of received message
    	byte[] receiveBuf = new byte[BUFSIZE];  // Receive buffer
    	
    	// Receive until client closes connection, indicated by -1 return
    	while ((recvMsgSize = in.read(receiveBuf)) != -1) {
    		out.write(receiveBuf, 0, recvMsgSize);
    	}
    	System.out.println( from.getLocalSocketAddress() + "cierra conexión");
    	from.close();  // Close the socket.  We are done with this client!
    }
    	
}
